<template>
    <div style="padding: 20px; max-width: 800px; margin: 0 auto; font-family: -apple-system, sans-serif;">
        <h1>📁 集合管理（简化版）</h1>

        <!-- 操作按钮 -->
        <t-space style="margin-bottom: 20px">
            <t-button theme="primary" @click="openModal(null)">新增集合</t-button>
        </t-space>

        <!-- 集合表格 -->
        <t-table :data="collections" :columns="columns" row-key="id" :pagination="pagination">
            <template #op="slotProps">
                <t-space>
                    <t-button size="small" theme="primary" @click="openModal(slotProps.row)">
                        编辑
                    </t-button>
                    <t-button size="small" theme="danger" @click="deleteCollection(slotProps.row.id)"
                        :disabled="collections.length <= 1">
                        删除
                    </t-button>
                </t-space>
            </template>
        </t-table>

        <!-- 空状态 -->
        <t-empty v-if="collections.length === 0" description="暂无集合" style="margin-top: 40px" />

        <!-- 弹窗 -->
        <t-dialog v-model:visible="modalVisible" :header="editing ? '编辑集合' : '新增集合'" @confirm="handleSubmit"
            @close="modalVisible = false">
            <t-form :data="form" @submit="handleSubmit">
                <t-form-item label="集合名称" name="name">
                    <t-input v-model="form.name" placeholder="请输入集合名称" />
                </t-form-item>
            </t-form>
        </t-dialog>
    </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue';
import { MessagePlugin } from 'tdesign-vue-next';
import { collectionDB } from './db';

// 集合列表
const collections = ref([]);

// 弹窗控制
const modalVisible = ref(false);
const editing = ref(false);
const form = ref({ name: '' });

// 分页
const pagination = ref({
    total: 0,
    pageSize: 10,
    current: 1,
    onChange: (pageInfo) => {
        pagination.value = { ...pagination.value, ...pageInfo };
    },
});

// 表格列
const columns = [
    { colKey: 'id', title: 'ID', width: 80 },
    { colKey: 'name', title: '集合名称' },
    { colKey: 'op', title: '操作', width: 150 },
];

// 加载数据
const loadData = async () => {
    let list = await collectionDB.getAll();
    // 转 id 为 number
    collections.value = list.map(c => ({ ...c, id: Number(c.id) }));

    // 如果没有集合，创建 default
    if (collections.value.length === 0) {
        const id = await collectionDB.add({ name: 'default' });
        collections.value = [{ id: Number(id), name: 'default' }];
    }

    pagination.value.total = collections.value.length;
};

// 打开弹窗
const openModal = (item) => {
    if (item) {
        form.value = { name: item.name };
        editing.value = true;
        editing.id = Number(item.id);
    } else {
        form.value = { name: '' };
        editing.value = false;
    }
    modalVisible.value = true;
};

// 提交表单
const handleSubmit = async () => {
    const name = form.value.name.trim();
    if (!name) {
        MessagePlugin.warning('集合名称不能为空');
        return;
    }

    if (editing.value) {
        await collectionDB.update({
            id: editing.id,
            name,
        });
        MessagePlugin.success('更新成功');
    } else {
        const id = await collectionDB.add({ name });
        collections.value.push({ id: Number(id), name });
        MessagePlugin.success('新增成功');
    }

    modalVisible.value = false;
    await loadData();
};

// 删除集合
const deleteCollection = async (id) => {
    if (collections.value.length <= 1) {
        MessagePlugin.warning('至少保留一个集合');
        return;
    }

    await collectionDB.delete(Number(id));
    MessagePlugin.success('删除成功');
    await loadData();
};

// 初始化
onMounted(async () => {
    await loadData();
});
</script>

<style>
body {
    margin: 0;
    padding: 0;
    background-color: #f5f6fa;
    color: #333;
}
</style>